package thread;
//进程安全
//进程相互重叠
public class demo15 {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Object num = new Object(){

        };
//        Thread t1 =  new Thread(()->{
//            for (int i = 0;i<50000;i++){
//                count++;
//            }
//        });
//        Thread t2 =  new Thread(()->{
//            for (int i = 0;i<50000;i++){
//                count++;
//            }
//        });
//        //线程出现相互重叠
//        t1.start();
//        t2.start();
//        t1.join();
//        t2.join();

        //解决一，先完成1，在完成2，用join阻塞
//        t1.start();
//        t1.join();
//        t2.start();
//        t2.join();

        //解决二，用synchronized加锁
        //用该方法加锁，需要定义对象，方便对该对象加锁

        Thread t1 =  new Thread(()->{
            for (int i = 0;i<50000;i++) {
                synchronized (num) {
                    count++;
                }
            }
        });
        Thread t2 =  new Thread(()->{
            for (int i = 0;i<50000;i++) {
                synchronized (num) {
                    count++;
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count"  + ":" + count);
    }
}
